package com.photoeditor.demo.model.filter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

import com.android.gpuimage.GPUImageFilter;
import com.common.base.ComponentContext;
import com.common.base.utils.CryptTool;
import com.photoeditor.R;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.imageloader.GlideApp;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.util.ImageCache;
import com.photoeditor.demo.util.LanguageManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by winn on 17/4/17.
 */

public class ImageFilterTools {

    public static final String FILTER_NAME_DEFAULT = ComponentContext.getContext().getResources().getString(R.string.original_filter);

    private final static Map<String , Integer> sInsideFilters;

    static {
        sInsideFilters = new HashMap<>();
        sInsideFilters.put("Artistic", R.raw.artistic);
        sInsideFilters.put("Frosty", R.raw.frosty);
    }

    public static StoreOnlineBean loadInsideFilterBean() {
        String cryptJson = LanguageManager.inputStream2String(ComponentContext.getContext().getResources().openRawResource(R.raw.insidefilter));
        String json = CryptTool.decrypt(cryptJson);
        JSONObject storeRootOnlineJson = null;
        try {
            storeRootOnlineJson = new JSONObject(json);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (storeRootOnlineJson == null) {
            return null;
        }
        return StoreOnlineBean.parse(storeRootOnlineJson, null);
    }

    public static String copyInsideFileToExternalPath(String categoryName) {
        AppApplication appApplication = AppApplication.getApplication();

        String filePath = generateFilterCategoryFilePath(categoryName);
        File file = new File(filePath);
        try {
            Integer integer = sInsideFilters.get(categoryName);
            if (integer != null) {
                InputStream inputStream = appApplication.getResources().openRawResource(integer);
                if (inputStream != null) {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    byte buf[] = new byte[8192];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        fileOutputStream.write(buf, 0, len);
                    }

                    fileOutputStream.close();
                    inputStream.close();
                    return filePath;
                }
            }
        } catch (IOException e1) {
        }

        return "";
    }


    public static String generateFilterCategoryFilePath(String categoryName) {
        String rootDir = com.common.base.utils.FileUtil.getExternalCacheDir(
                ComponentContext.getContext(),
                "downloadtmp", true);

        String name = categoryName + String.valueOf(System.currentTimeMillis());
        name = ImageCache.hashKeyForDisk(name);
        return rootDir + "/" + name + ".zip";
    }

    /**
     * @param context
     * @param data 当前的位置
     * @return
     */
    public static GPUImageFilter createFilterForType(final Context context, FilterBean data) {
        if(data != null) {
            int type = data.getType();
            if(type == FilterConstant.TYPE_DOWNLOAD || type == FilterConstant.TYPE_ARTISTIC){
                GPUImageFilter filter =  FilterPluginsHelper.loadFilterPlugin(context, data.getApkUri(), data.getPackageName());
                return filter;
            } else if(type == FilterConstant.TYPE_ORIGINAL){//如果是Original类型  特殊处理
                return new GPUImageFilter();
            }
        } else {
            return new GPUImageFilter();
        }
        return null;
    }

    /**
     * 获取下载包中的Drawable并显示  如果获取不到则去请求
     */
    public static void setImage(ImageView imageView, Context context, String pkgName, String path, String url){
        Drawable drawable = FilterPluginsHelper.getFilterIcon(context, path, pkgName);
        if(drawable == null) {
            ImageLoader.loadImage(url, R.drawable.ic_default_image, imageView);
            return;
        }
        GlideApp.with(ComponentContext.getContext())
                .load(drawable)
                .placeholder(R.drawable.ic_default_image)
                .into(imageView);
    }

    public static ArrayList<FilterBean> getFilterData(Context context) {
        //从sqlite获取滤镜数据
        ArrayList<FilterBean> filterList = DataManager.getInstance().getLocalFilterListStatusUse();
        FilterBean original = new FilterBean();
        original.setName("Original");
        original.setType(FilterConstant.TYPE_ORIGINAL);
        original.setPackageName("com.star.camera.imagefilter.plugins.original");
        filterList.add(0, original);
        return filterList;
    }

    /**
     * 重置滤镜强度
     *
     * @param filter
     */
    public static void resetFilterIntensity(GPUImageFilter filter) {
        if (filter == null) {
            return;
        }
        if (filter.isSupportIntensity()) {
            filter.setIntensity(1f);
        } else {
            filter.setIntensity(1f);
        }
    }

    /**
     * 获取滤镜强度
     *
     * @param filter
     * @return
     */
    public static float getFilterIntensity(GPUImageFilter filter) {
        if (filter == null) {
            return 1f;
        }
        return filter.getIntensity();
    }

    public static void setFilterIntensity(GPUImageFilter filter, float intensity) {
        if (filter == null) {
            return;
        }
        filter.setIntensity(intensity);
    }
}
